package com.linkai.controller.admin.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linkai.controller.admin.BaseController;
import com.linkai.dto.admin.business.InputOrderUpdateDto;
import com.linkai.dto.admin.business.sale.ProductShowDto;
import com.linkai.entity.Bproduct;
import com.linkai.entity.Inputorder;
import com.linkai.entity.InputorderProduct;
import com.linkai.entity.Storage;
import com.linkai.enums.ResultDTO;
import com.linkai.service.BproductService;
import com.linkai.service.InputorderProductService;
import com.linkai.service.InputorderService;
import com.linkai.service.StorageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author yamon
 * @Date 2021-02-20 20:51
 * @Description 库存所有的操作
 * @Version 1.0
 */
@Controller
@RequestMapping("/admin/business/storage")
public class StorageController extends BaseController {

    @Autowired
    private InputorderService inputorderService;
    @Autowired
    private InputorderProductService inputorderProductService;
    @Autowired
    private BproductService productService;
    @Autowired
    private StorageService storageService;
    /**
     * 跳转入库页面，进货单那块
     * @param id
     * @return
     */
    @GetMapping("/input/{id}")
    public ModelAndView input(@PathVariable Integer id) {
        final ModelAndView modelAndView = new ModelAndView();
        //查出来商品和进货单信息
        InputOrderUpdateDto inputOrderUpdateDto = inputorderService.selectInputOrderDto4UpdateById(id);
        modelAndView.addObject("inputOrder",inputOrderUpdateDto);
        modelAndView.setViewName("admin/business/inputOrder/storage/storage");
        return modelAndView;
    }

    /**
     * 入库
     * @param id id 进货单id
     * @return
     */
    @PostMapping("/add/{id}")
    @ResponseBody
    public ResultDTO<Boolean> add(@PathVariable Integer id){
        //进货前先查找是否可以已经进库存了，如果已经进过了，直接相加即可
        //找到对应的商品
        final QueryWrapper<InputorderProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("input_order_id",id);
        final List<InputorderProduct> inputorderProducts = inputorderProductService.list(queryWrapper);
        final Inputorder inputorder = inputorderService.getById(id);
        Integer bstoId = inputorder.getBstoId();
        //得到对应的商品id
        inputorderProducts.forEach(inputorderProduct -> {
            if (isExistProductByStoreSupplier(inputorderProduct.getProductId(),bstoId, inputorder.getSupId(),inputorderProduct.getInpordPrice())){
                //如果已经存在，则直接更新
                storageService.updateStorageByProId(inputorderProduct.getProductId(),inputorderProduct.getInpordNum(),inputorderProduct.getEachSum(),bstoId, inputorder.getSupId(),inputorderProduct.getInpordPrice());
            }else{
                //得到商品
                final Bproduct bproduct = productService.getById(inputorderProduct.getProductId());
                //新增
                Storage storage = new Storage();
                storage.setProTitle(bproduct.getBproTitle());
                storage.setProUnit(bproduct.getBproUnit());
                storage.setProId(inputorderProduct.getProductId());
                storage.setProNum(inputorderProduct.getInpordNum());
                storage.setProMoney(inputorderProduct.getEachSum());
                storage.setProPrice(inputorderProduct.getInpordPrice());
                storage.setBstoId(bstoId);
                storage.setSupId(inputorder.getSupId());
                storage.setState(1);
                storageService.save(storage);
            }
        });
        //如果都已经入库了，更改进货单状态
        final Inputorder entity = new Inputorder();
        entity.setId(id);
        entity.setInpState(1);
        return super.successSaveInfo(inputorderService.updateById(entity));
    }

    /**
     * 根据商品id，仓库，供应商，进货价确定库存是否有同样的商品，如果有的话，直接更新就行，没有的话，需要新增一条货物
     * @param proId 商品id
     * @param bstoId 仓库id
     * @param supId 供应商id
     * @param inpordPrice 进价
     * @return 存在
     */
    private boolean isExistProductByStoreSupplier(Integer proId, Integer bstoId, Integer supId, BigDecimal inpordPrice) {
        final QueryWrapper<Storage> wrapper = new QueryWrapper<>();
        wrapper.eq("pro_id",proId);
        wrapper.eq("bsto_id",bstoId);
        wrapper.eq("sup_id",supId);
        wrapper.eq("pro_price",inpordPrice);
        int count = storageService.count(wrapper);
        return count != 0;
    }


    /**
     * 查找出所有的库存信息
     *
     * @return list
     */
    @RequestMapping(value = "/product/listAll", method = RequestMethod.GET)
    @ResponseBody
    public List<ProductShowDto> getAllProduct() {
        final List<Storage> list = storageService.list();
        List<ProductShowDto> productDtos = new ArrayList<>();
        list.forEach(product -> {
            final ProductShowDto target = new ProductShowDto();
            BeanUtils.copyProperties(product, target);
            productDtos.add(target);
        });
        return productDtos;
    }



}
